var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
// var env = process.env.NODE_ENV || "development";
var config = require("../config/dbConfig");

var db = {
  reset : function () {
    if (db.sequelize) {
      db.sequelize.close();
    }
    initDB();
  },
  handlerDBError : function (error){
      if (error){
          if (error.name === 'SequelizeDatabaseError' && error.message === 'read ECONNRESET') {
              db.reset();
          }
          // you can handler other database error
      }

  }
};

function initDB (){
    var sequelize = new Sequelize(config.database, null, null, Object.assign({
            dialect: 'mysql'
        }, config
    ));
    fs
        .readdirSync(__dirname)
        .filter(function(file) {
            return (file.indexOf(".") !== 0) && (file !== "index.js") ;
        })
        .forEach(function(file) {
            var model = sequelize.import(path.join(__dirname, file));
            db[model.name] = model;
        });

    Object.keys(db).forEach(function(modelName) {
        if ("associate" in db[modelName]) {
            db[modelName].associate(db);
        }
    });

    db.sequelize = sequelize;
    db.Sequelize = Sequelize;

}

initDB();

module.exports = db;